﻿using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.JSInterop;
using System.Diagnostics.CodeAnalysis;
using System.Reflection.Metadata;
using TrackSystem.Contracts;
using TrackSystem.Entities.Dtos.Slave;
using TrackSystem.Entities.Extensions;
using TrackSystem.Entities.Models;
using TrackSystem.IO.Utils;

namespace TrackSystem.UI.Server.Units
{
    public partial class SlaveDefView
    {

        [Parameter]
        public SlaveDto Slave { get; set; }


        [Parameter]
        public HubConnection hub { get; set; }

        [Inject]
        [NotNull]
        private ToastService? ToastService { get; set; }

        [NotNull]
        private Modal? SizeSmallModal { get; set; }

        private IEnumerable<SelectedItem> _nameItems = [];
        private string _sMessage = "";


        private readonly Dictionary<SlaveProtocol, string> _ptlItems = new()
        {
            {SlaveProtocol.Modbus_RTU, "MODBUS-RTU"},
             {SlaveProtocol.Modbus_TCP, "MODBUS-TCP"},
            {SlaveProtocol.USERDEFINED, "自定义"},
        };

        private readonly Dictionary<PortCategory, string> _portItems = new()
        {
            {PortCategory.TCP,  "TCP" },
            {PortCategory.UDP,  "UDP" },
            {PortCategory.SRIAL, "串口" }
        };

        private readonly SelectedItem[] _serialParamsItems =
        [
            new ("1", "N-8-1"),
            new ("2", "E-8-1"),
            new ("3", "O-8-1"),
            new ("4", "N-7-1"),
            new ("5", "E-7-1"),
            new ("6", "O-7-1"),
            new ("7", "N-7-1.5"),
            new ("8", "E-7-1.5"),
            new ("9", "O-7-1.5"),
        ];

        private bool _bEditStatus = true;
        private bool _bInsertStatus = false;

        private SlaveDto _tempSlave;    // 保存暂时数据



        private Task OnPtlChanged(SlaveProtocol e)
        {
            _tempSlave.Protocol = e;
            return Task.CompletedTask;
        }

        private Task OnPortChanged(PortCategory e)
        {
            _tempSlave.PortCategory = e;
            return Task.CompletedTask;
        }


        private async Task BtnClickEdit()
        {
            try
            {
                if (hub.State == HubConnectionState.Connected)
                {
                    hub.On<List<string>>("RevVarNames", async (tt) =>
                    {
                        _nameItems = tt.Select(c => new SelectedItem(c, c)).ToList();
                        _tempSlave = SlaveDto.Clone(Slave);
                        _bEditStatus = false;
                        await InvokeAsync(StateHasChanged);
                    });

                    await hub.SendAsync("GetVarNames");
                    _sMessage = "";
                }
            }
            catch (Exception ex)
            {
                await ToastService.Error($"{DateTime.Now:u} 从站{Slave.Name}", $"获取变量名错误, {ex.Message}");
            }
        }

        private async Task BtnClickSave()
        {
            try
            {
                if (hub.State == HubConnectionState.Connected)
                {
                    hub.On<ApiResult<SlaveTable>>("HandleSaveSlave", async (result) =>
                    {
                        if (result.Success)
                        {
                            Slave = _tempSlave;
                            Slave.Id = result.Data?.Id ?? 0;
                            // await ToastService.Success($"从站{Slave.Name}", "参数保存成功");
                            _sMessage = $"{DateTime.Now:u} 从站{Slave.Name}参数保存成功";
                            _bEditStatus = true;
                            _bInsertStatus = false;
                        }
                        else
                        {
                            // await ToastService.Error($"从站{Slave.Name}", result.Message);
                            _sMessage = $"{DateTime.Now:u} 从站{Slave.Name}参数保存失败, {result.Message}";
                        }
                        await InvokeAsync(StateHasChanged);
                    });

                    if (!_bEditStatus)
                        await hub.SendAsync("SaveSlaveAsync", _tempSlave);
                    if (_bInsertStatus)
                        await hub.SendAsync("InsertSlaveAsync", _tempSlave);
                }
            }
            catch (Exception ex)
            {
                // await ToastService.Error($"从站{Slave.Name}", $"参数保存错误, {ex.Message}");
                _sMessage = $"{DateTime.Now:u} 从站{Slave.Name}参数保存失败, {ex.Message}";
                await InvokeAsync(StateHasChanged);
            }
        }

        private Task BtnClickCancel()
        {
            _sMessage = "";
            _bEditStatus = true;
            _bInsertStatus = false;
            return Task.CompletedTask;
        }

        private async Task OnDeleteSlaveAsync()
        {
            _sMessage = "";
            // await ToastService.Error($"从站{Slave.Name}", $"参数删除错误!");
            _sMessage = $"{DateTime.Now:u} 从站{Slave.Name}参数删除错误";
            await InvokeAsync(StateHasChanged);
        }

        private Task OnParamChanged(SelectedItem item)
        {
            _tempSlave.SerialParams = item.Text;
            return Task.CompletedTask;
        }

        private Task OnRoInsertReg(SelectedItem item)
        {
            _tempSlave.RoList += string.IsNullOrEmpty(_tempSlave.RoList)? item.Text : ("," + item.Text);
            StateHasChanged();
            return Task.CompletedTask;
        }

        private Task OnRwInsertReg(SelectedItem item)
        {
            _tempSlave.RwList += string.IsNullOrEmpty(_tempSlave.RwList)? item.Text : ("," + item.Text);
            StateHasChanged();
            return Task.CompletedTask;
        }

        private async Task BtnClickInsert()
        {
            try
            {
                if (hub.State == HubConnectionState.Connected)
                {
                    hub.On<List<string>>("RevVarNames", async (tt) =>
                    {
                        _nameItems = tt.Select(c => new SelectedItem(c, c)).ToList();
                        _tempSlave = new SlaveDto { Name = "UserServer" };
                        _bInsertStatus = true;
                        await InvokeAsync(StateHasChanged);
                    });

                    await hub.SendAsync("GetVarNames");
                    _sMessage = "";
                }
            }
            catch (Exception ex)
            {
                _sMessage = $"{DateTime.Now:u} 从站{Slave.Name}获取变量名错误，, {ex.Message}";
                await InvokeAsync(StateHasChanged);
                // await ToastService.Error($"从站{Slave.Name}", $"获取变量名错误, {ex.Message}");
            }
        }
    }
}
